function modulated_signal = modulate_data(data, M)
% modulate_data - 对输入比特流进行数字调制
%
% 输入参数:
%   data - 输入的比特流
%   M    - 调制阶数 (如：2-BPSK, 4-QPSK, 16-16QAM等)
%
% 输出参数:
%   modulated_signal - 调制后的信号

% 根据调制方式进行处理
switch M
    case 2  % BPSK调制
        % 将0,1映射为-1,1
        modulated_signal = 2*data - 1;
        
    case 4  % QPSK调制
        % 将比特分组
        reshape_size = floor(length(data)/2)*2;  % 确保比特数为偶数
        data_reshaped = data(1:reshape_size);
        data_reshaped = reshape(data_reshaped, 2, [])';
        
        % 将比特对映射为QPSK符号
        mapping = [-1-1i, -1+1i, 1-1i, 1+1i] / sqrt(2);  % 归一化能量
        decimal = bin2dec(char(data_reshaped + '0'));
        modulated_signal = mapping(decimal + 1);
        
    case 16  % 16QAM调制
        % 将比特分组
        reshape_size = floor(length(data)/4)*4;  % 确保比特数为4的倍数
        data_reshaped = data(1:reshape_size);
        data_reshaped = reshape(data_reshaped, 4, [])';
        
        % 创建16QAM星座图
        mapping = zeros(16,1);
        for i = 0:15
            % 将十进制值转换为格雷码映射的复数值
            b = de2bi(i, 4);
            
            % 计算实部和虚部
            real_part = 2*(1-b(1)) - 1;
            if b(2) == 0
                real_part = real_part * 3;
            end
            
            imag_part = 2*(1-b(3)) - 1;
            if b(4) == 0
                imag_part = imag_part * 3;
            end
            
            mapping(i+1) = (real_part + 1i*imag_part) / sqrt(10);  % 归一化能量
        end
        
        % 将比特组映射为16QAM符号
        decimal = bin2dec(char(data_reshaped + '0'));
        modulated_signal = mapping(decimal + 1);
        
    otherwise
        error('不支持的调制方式: M = %d', M);
end

end 